package com.example.yan.excel_split.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;


import java.math.BigDecimal;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class demo4 {


    public static void main(String[] args) {

        //  ExcelReader fileReader = ExcelUtil.getReader(" E:\\桌面\\SHOP.105110000000005.20211013.02.success(1).xls");
        ExcelReader fileReader = ExcelUtil.getReader("C:\\Users\\75763\\Desktop\\SHOP.105110000000005.20211013.02.success(1).xls");
        List<List<Object>> readAll = fileReader.read();

        String header = null;

        for (List<Object> objects : readAll) {
            //迭代删除空格
            Iterator<Object> it = objects.iterator();

            while (it.hasNext()) {
                Object next = it.next();
                if (next == null || StringUtils.isBlank(next.toString())) {
                    it.remove();
                }
            }
            System.out.println("JSON==>" + JSON.toJSONString(objects));

            String merchantCode = JSON.toJSONString(objects);

            if (merchantCode.contains("商户编号") && merchantCode.contains("商户地址")) {
                System.out.println("merchantCode==>" + merchantCode);
                //把所有的中括号取消
                String str = merchantCode.substring(merchantCode.indexOf("[") + 1, merchantCode.lastIndexOf("]"));
                String st = "商户/部门编号:" + str.substring(12, 26);
                header = st;
            }


        }
        String[] keyArr = new String[]{"终端号", "发卡行", "卡种", "卡号-序列号", "交易日期", "交易时间", "交易类型", "授权号", "交易金额", "小费",
                "分期期数", "银行手续费", "DCC返还手续费", "划账金额", "凭证号", "批次号", "POS交易序号", "结算账号", "订单号"
                , "柜台编号", "系统参考号", "持卡人姓名", "付款凭证号", "备注1", "备注2"};

        JSONArray array = new JSONArray();

        for (List<Object> aLinelist : readAll) {
            if (aLinelist.size() < keyArr.length)//匹配数据长度 长度不足不要
                continue;
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < keyArr.length; i++) {
                if (i < aLinelist.size()) {
                    Object property = aLinelist.get(i);
                    map.put(keyArr[i], property);
                }

            }
            array.add(map);
        }
        System.out.println("==>" + array);


        // 你要是拿序号 1、可以把最外层这个循环 for (int i = 0; i < zdh.length(); i++) {
        // 2、你可以定义一个变量
        int i = 1;
        BigDecimal total = new BigDecimal("0");// 合计金额

        //  JSONArray listA = new JSONArray();//A消费


        JSONArray listA = new JSONArray();//A消费
        JSONArray listB = new JSONArray();//B消费
        JSONArray listC = new JSONArray();//C消费
        JSONArray listzdh = new JSONArray();//终端号
        BigDecimal totaA = new BigDecimal("0");
        BigDecimal totaB = new BigDecimal("0");
        BigDecimal totaC = new BigDecimal("0");

        List<String> yyy = new ArrayList<>();
        for (Object object0 : array) {
            JSONObject jsonObject = JSON.parseObject(object0.toString());
            String zdh = jsonObject.getString("终端号");
            yyy.add(zdh);
        }
        ArrayList<Object> list2 = new ArrayList<>();
        yyy = zdh(yyy);
        for (String ttt : yyy) {
            if (!ttt.contains("终端号")) {
                System.out.println("yyy222" + ttt);
                list2.add(ttt);
            }

        }
        System.out.println("--" + list2);


        for (Object object : array) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            Map<String, Object> row2 = new LinkedHashMap<>();
            Map<String, Object> row3 = new LinkedHashMap<>();
            JSONObject jsonObject = JSON.parseObject(object.toString());

            String zdh = jsonObject.getString("终端号");
            String fkh = jsonObject.getString("发卡行");
            String kz = jsonObject.getString("交易金额");
            String jylx = jsonObject.getString("交易类型");

            listzdh.add(zdh);
            //   System.out.println("终端号+" + zdh + fkh + kz);


            if (!zdh.contains("终端")) {

                //   row1.put("序号", i++);
                row1.put("终端号", zdh);
                row1.put("发卡行", fkh);
                row1.put("交易金额", kz);
                row1.put("交易类型", jylx);
            }

            if (!zdh.contains("终端")) {
                //  row2.put("序号", i++);
                row2.put("终端号", zdh);
                row2.put("发卡行", fkh);
                row2.put("交易金额", kz);
                row2.put("交易类型", jylx);
                total = total.add(new BigDecimal(kz));
            }

            if (!zdh.contains("终端")) {
                // row3.put("序号", i++);
                row3.put("终端号", zdh);
                row3.put("发卡行", fkh);
                row3.put("交易金额", kz);
                row3.put("交易类型", jylx);
                total = total.add(new BigDecimal(kz));

            }

            switch (jylx) {
                case "消费":
                    totaA = totaA.add(new BigDecimal(kz));
                    listA.add(row1);
                    break;
                case "银联二维码消费(被扫)":
                    totaB = totaB.add(new BigDecimal(kz));
                    listB.add(row2);
                    break;
                case "外卡消费":
                    totaC = totaC.add(new BigDecimal(kz));
                    listC.add(row3);
                    break;
            }

        }


        for (Object listA2 : listA) {
            JSONObject aaa = JSON.parseObject(listA2.toString());
            Object o = aaa.get("终端号");
            for (int j = 0; j < aaa.size(); j++) {
                for (int k = 0; k <list2.size() ; k++) {
                    if (list2.get(k).equals(o)) {
                        System.out.println("666" + listA2);
                    }
                }
            }


        }


//        Map<String, List<Map>> groupBy = listA.stream().collect(Collectors.groupingBy(map
//                -> {return (String)map.get("发卡行");}));
//
//        System.out.println(groupBy);
//        List list3 = new ArrayList();
//        groupBy.keySet().forEach(o -> {
//            List<Map> list21 = groupBy.get(o);
//            double q = 0D;
//            for (Map map : list21) {
//                q = q + (double)map.get("交易金额");
//                list3.add(map);
//            }
//            Map map1 = new HashMap();
//            map1.put("发卡行","终端小计算(不含退货)");
//            map1.put("交易金额",q);
//            list2.add(map1);
//            System.out.println(list2);
//            list3.add(map1);
//        });


        if (listA.size() > 0) {
            JSONObject totalA = new JSONObject();
            totalA.put("终端号", "终端小计算(不含退货)");
            totalA.put("发卡行", "");
            totalA.put("交易金额", totaA);
            listA.add(totalA);
            //List<JSONObject> list = JSONObject.parseArray(com.alibaba.fastjson.JSONArray.toJSONString(listA),JSONObject.class);
            System.out.println("listA" + listA);
            exportExcel(listA, "A消费类型", header);
        }

//
//        if (listB.size() > 0) {
//            JSONObject totalB = new JSONObject();
//            totalB.put("终端号", "终端小计算(不含退货)");
//            totalB.put("发卡行", "");
//            totalB.put("交易金额", totaB);
//            listB.add(totalB);
//            exportExcel(listB, "B消费类型", header);
//        }
//
//        if (listC.size() > 0) {
//            JSONObject totalC = new JSONObject();
//            totalC.put("终端号", "终端小计算(不含退货)");
//            totalC.put("发卡行", "");
//            totalC.put("交易金额", totaC);
//            listC.add(totalC);
//            exportExcel(listC, "C消费类型", header);
//
//        }
//
//        listA.addAll(listB);
//        listA.addAll(listC);
//        if (listA.size() > 0) {
//            exportExcel(listA, "合计", header);
//        }

        System.out.println("文件生成成功为止在= E:\\桌面\\新建文件夹(4)\\888881.xlsx");
    }


    private static void exportExcel(List<Object> list, String fileName, String header) {

        Date date = new Date();

        ExcelWriter writer = ExcelUtil.getWriter("E:\\桌面\\新建文件夹(4)\\" + exportDate(date) + fileName + ".xlsx");


        ArrayList<Object> rows4 = CollUtil.newArrayList(list);
// 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
// 合并单元格后的标题行，使用默认标题样式
        writer.merge(3, header);
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows4, true);
        // 关闭writer，释放内存
        writer.close();
    }


    //获取当下时间
    private static String exportDate(Date date) {

        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
        //   sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
        sdf.applyPattern("yyyyMMdd");
        //  Date date = new Date();// 获取当前时间
        System.out.println("现在时间：" + sdf.format(date)); //

        return sdf.format(date);

    }


    public static List<String> zdh(List<String> list) {

        List<String> myList = list.stream().distinct().collect(Collectors.toList());
        System.out.println("==>" + myList);
        return myList;
    }


}
